/**
 * Copyright(c) kyle.
 */
package org.example.tomcat.bio.business;

import org.example.tomcat.bio.basic.GPRequest;
import org.example.tomcat.bio.basic.GPResponse;
import org.example.tomcat.bio.basic.GPServlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 启动类
 *
 * @author kyle
 * @version 1.00.00
 * @since [2020-10-20 19:57]
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2020-10-20 19:57]
 */
public class GPTomcat {
    private final int port = 49090;
    private final Map<String, GPServlet> mStringGPServletMap = new HashMap<>(2);
    private final Properties webxml = new Properties();
    private ServerSocket server;

    public static void main(String[] args) {
        new GPTomcat().start();
    }

    /**
     * 加载sevlet
     *
     * @throws Exception
     */
    private void init() throws Exception {
        String WEB_INF = ".\\src\\main\\java\\org\\example\\tomcat\\bio\\resouce\\";
        FileInputStream fis = new FileInputStream(WEB_INF + "web.properties");
        webxml.load(fis);
        for (Object k : webxml.keySet()) {
            String key = k.toString();
            if (key.endsWith(".url")) {
                String servletName = key.replaceAll("\\.url$", "");
                String url = webxml.getProperty(key);
                String className = webxml.getProperty(servletName + ".className");
                GPServlet obj = (GPServlet) Class.forName(className).newInstance();
                mStringGPServletMap.put(url, obj);
            }
        }
    }

    public void start() {
        try {
            init();
            server = new ServerSocket(port);
            System.out.println("Tomcat已启动，监听端口是" + port);
            while (true) {
                Socket client = server.accept();
                process(client);
            }
        } catch (Exception pE) {
            pE.printStackTrace();
        }
    }

    private void process(final Socket pClient) throws Exception {
        InputStream is = pClient.getInputStream();
        OutputStream os = pClient.getOutputStream();
        GPRequest lvGPRequest = new GPRequest(is);
        GPResponse lvGPResponse = new GPResponse(os);

        String url = lvGPRequest.getUrl();

        if (mStringGPServletMap.containsKey(url)) {
            mStringGPServletMap.get(url).service(lvGPRequest, lvGPResponse);
        } else {
            lvGPResponse.write("404 - Not Found");
        }

        os.flush();
        os.close();
        is.close();
        pClient.close();
    }
}
